package com.joy;

import com.google.common.base.Strings;
import com.google.common.collect.Lists;
import com.joy.common.DBTYPE;
import com.joy.common.JdbcMeta;
import org.apache.commons.cli.*;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;

import java.io.*;
import java.sql.*;
import java.util.ArrayList;
import java.util.List;

/**
 * Hello world!
 *
 */
public class App 
{
    private static final Logger LOGGER = LogManager.getLogger(LogManager.ROOT_LOGGER_NAME);
    public static HelpFormatter help = new HelpFormatter();
    public static void main( String[] args )
    {
        String CMDLineSyntax = "example: -dbtype mssql -filename retail/yhspbi -shema cc  -dbname demo  -username SA -password Welcome1 -host localhost -port 1433 ";
        Options opts = new Options();
        opts.addOption(new Option("h", "help",  false, "print help for the command."));
        opts.addOption(Option.builder("dbtype").required().hasArg().desc("source database type,now support MYSQL,ORACLE,MSSQL ").build());
        opts.addOption(Option.builder("dbname").required().hasArg().desc("source database name or service name or tnsname depend on dbtype").build());
        opts.addOption(Option.builder("tables").hasArgs().optionalArg(true).valueSeparator(',').argName("table1,table2,table3").desc("if not specified select all tables").build());
        opts.addOption(Option.builder("host").hasArg().desc("source database hostname ").build());
        opts.addOption(Option.builder("port").hasArg().desc("source database port ").build());
        opts.addOption(Option.builder("shema").required().hasArg().desc("target shema").build());
        opts.addOption(Option.builder("filename").required().hasArg().desc("table name file ").build());
        opts.addOption(Option.builder("username").required().hasArg().desc("database username").build());
        opts.addOption(Option.builder("password").required().hasArg().desc("database password").build());
        CommandLineParser parser = new DefaultParser();
        CommandLine line = null;
        try {
            line = parser.parse(opts, args);
            if(line.hasOption("h")){
                help.printHelp(CMDLineSyntax, opts);
            }

            String dbtype = line.getOptionValue("dbtype");
            String dbname = line.getOptionValue("dbname");
            String host = line.getOptionValue("host");
            String port = line.getOptionValue("port");
            String[] tables = line.getOptionValues("tables");
            String username = line.getOptionValue("username");
            String password = line.getOptionValue("password");
            String shema = line.getOptionValue("shema");
            String filename = line.getOptionValue("filename");

            String jdbcurl = null;
            DBTYPE c_dbtype = DBTYPE.valueOf(dbtype.toUpperCase());
            try{

                String driverName = JdbcMeta.DRIVER_NAME.get(c_dbtype);
                if (Strings.isNullOrEmpty(driverName))  throw new Exception("can't get the  driver name of  the"+ dbtype);
                Class.forName(driverName);

                String jdbcTpl = JdbcMeta.JDBCURL_TPL.get(c_dbtype);
                if (Strings.isNullOrEmpty(driverName))  throw new Exception("can't get the jdbc url of  the"+ dbtype);

                if(c_dbtype.equals(DBTYPE.ADW)){

                }else{

                }
                switch (c_dbtype){
                    case  ADW: jdbcurl = String.format(jdbcTpl,dbname); break;
                    case  ORACLE:jdbcurl = String.format(jdbcTpl,host,port,dbname); break;
                    case  MYSQL: jdbcurl = String.format(jdbcTpl,host,port,dbname); break;
                    case  MSSQL:  jdbcurl = String.format(jdbcTpl,host,port,dbname); break;
                    default: throw new Exception("not support database");
                }
                System.out.println(jdbcurl);
            }catch(Exception e){
                LOGGER.error(e.getMessage());
            }


            List<String> tablenames = readTableName(filename);

            try {
                Connection conn = DriverManager.getConnection(jdbcurl,username,password);
                writercount(tablenames,shema,c_dbtype,conn);
//                String catalog = conn.getCatalog();
//                String schema = conn.getSchema();
//                DatabaseMetaData dbmd = conn.getMetaData();
//
//                List<String> tablenames =  new ArrayList<>();
//                String[] types = { "TABLE" };
//                ResultSet rs = dbmd.getTables(catalog, schema, "%", types);
//
//                while (rs.next()) {
//                    String tableName = rs.getString("TABLE_NAME");  //表名
//                    tablenames.add(tableName);
//                }
//                FileWriter writer = new FileWriter(dbtype+"_table.csv",true);
//                for(String tablename: tablenames){
//                    writer.write(tablename+"\n");
//                    writer.flush();
//                }
//                writer.close();
            } catch (Exception e) {
                e.printStackTrace();
            }
        } catch (ParseException | IOException e) {
            help.printHelp(CMDLineSyntax, opts);
        }
    }


    private static List<String> readTableName(String shema) throws IOException {
        String filename = shema+"_table.csv";
        InputStream path = ClassLoader.getSystemResourceAsStream(filename);
        BufferedReader reader = new BufferedReader(new InputStreamReader(path));
        String line = null;
        List<String> tablenames = Lists.newArrayList();
        while ((line = reader.readLine()) != null) {
            tablenames.add(line);
        }
        return tablenames;
    }

    private static void writercount(List<String> tablenames,String shema,DBTYPE dbtype,Connection conn) throws  Exception  {
        FileWriter writer = new FileWriter(shema+"_count_table.csv",true);
        Statement statement = conn.createStatement();
        for(String tablename: tablenames){
            ResultSet rs =  statement.executeQuery("select count(*) from "+shema+"."+tablename);
            long count = 0;
            if(rs.next()){
                count = rs.getLong(1);
            }
            rs.close();
            writer.write(tablename+","+count+"\n");
            writer.flush();
        }
        conn.close();
        writer.close();
    }
}
